<!--
  @Descripttion：编辑导入任务
  @Author：zqy
  @Date：2020-12-08 20:18:12
  @Last Modified by：zqy
  @Last Modified time：2020-12-08 20:18:12
-->
<template>
  <div class="qup-page-container">
    <div class="qup-page-header bread-box">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item @click.native="goBack"><span class="btn-green">导入任务</span></el-breadcrumb-item>
        <el-breadcrumb-item>任务编辑</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click.native="goBack">返回</el-button>
        
        <!-- v-if="basicData.importState==30 || basicData.importState==50" 30 校验中 ， 50 写入中 {{importStateName}} -->
        <el-button size="mini" @click="refreshTaskStatus">刷新</el-button>
        <template v-if="basicData.importState==40">
          <!--40 校验完成 basicData.importState==40-->
          <el-button size="mini" type="primary" @click="handleResetCheck">重新校验</el-button>
        </template>
        <template v-if="noPassNum===0 && basicData.importState==40">
          <!--40 校验完成 basicData.importState==40-->
          <el-button size="mini" type="primary" @click="handleImportTask">执行导入</el-button>
        </template>
        <template v-if="[10,20,30,40].indexOf(basicData.importState)>=0">
          <!--[10 导入中 , 20 导入完成, 30 校验中 , 40 校验完成]可操作终止任务-->
          <el-button size="mini" type="primary" @click="handleStopTask">终止任务</el-button>
        </template>
      </div>
    </div>
    <div class="qup-page-content">
      <el-scrollbar class="qup-page-scrollbar">
        <div class="qup-title-box"><span class="border" /><span>任务基础信息</span></div>
        <detail-basic :detail-data="basicData" :error-num="noPassNum" :total-num="totalNum" />

        <div class="qup-title-box">
          <span class="border" /><span>待处理数据</span>
          <el-checkbox v-model="onlyAbnormal" style="margin-left:20px">只查询异常行</el-checkbox>
        </div>
        <!-- 列表块 -->
        <table-box
          v-if="isHeaderLoad"
          ref="refTable"
          table-size="small"
          :table-max-height="500"
          :other-filters="otherFilters"
          :selected-arry.sync="tableSelected"
          :table-config="tableConfig"
          no-request
          show-selection
          @selection-change="handleSelectionChange"
          @btnOperate="btnOperate"
        >
          <!-- <el-table-column slot="before" fixed="left" label="序号" type="index" /> -->
          <!-- <el-table-column v-for="(column,index) in extColumnList" :key="index" :label="column.attributeName" :min-width="150" column-type="text">
                  <template v-slot="{row}">
                    {{ getExtColumnValue(row.extAttributeColumns,column.attributeField) }}
                  </template>
                </el-table-column> -->
        </table-box>
        <!-- 列表块 -->
      </el-scrollbar>
    </div>
    <edit-form
      v-if="showAddDialog"
      :visible.sync="showAddDialog"
      :ext-column-list="customColumnList"
      :detail-data="activeRow"
      :excelTaskId="taskBasic.id"
      :task-config="taskConfig"
      @success="handleSubmitSuccess"
    />
    <export-files 
      v-if="exportisible"
      title="导出待处理数据" 
      :visible.sync="exportisible"
      :config="exportConfig"
    />
  </div>
</template>

<script>
import { queryTaskDetail,queryTableExtColumn, deleteTaskRowData,taskRowCheck,queryTotalNum,queryNotCheckPassNum, taskResetCheck, taskImport, taskStop } from './api'
import DetailBasic from './components/DetailBasic'
import EditForm from './components/EditForm'
import {getApiPrefix } from './api'
export default {
  name: 'EditImportTask',
  components: { DetailBasic, EditForm },
  props: {
    pageShow: {
      type: Boolean,
      default: false
    },
    taskBasic: {
      type: [Object, String],
      default: ''
    },
    taskConfig:{
      type:Object,
      default:()=>{
        return {
          apiPrefix:'',// 应用接口前缀,如:ucenter,po-center,top-purchase
          checkRowApi:'',//行校验接口地址(后端提供)
          checkApi:'', //全量检查业务（自定义接口，后端提供）
          completeApi:'',//任务完成执行（回写业务操作）
          exportTempApi:'',// 临时数据导出接口
          taskFiltersRaw:[],  // 任务查询条件
          saveTempEmpty:false,// 是否保存null值为空字符串
          saveTempApi:'',//自定义临时数据保存接口
        }
      }
    }
  },
  data() {
    return {
      taskId: '', // 任务ID
      basicData: '',
      onlyAbnormal: false, // 是否只查询失败的数据行
      extColumnList: [], // 动态列
      isHeaderLoad:false,//表头是否加载完成
      tableDefaultSetting: [{
        prop: 'state',
        label: '检验结果',
        minWidth: '1150',
        formatData:({state})=>{
          const obj={
            '0':'未检查',
            '1':'检查通过',
            '-1':'未检查通过'
          }
          return obj[state]
        }
      },
      {
        prop: 'excelRowError',
        label: '检验结果说明',
        minWidth: '150'
      }],
      tableConfig: {
        interfacePath: `${getApiPrefix(this.taskConfig.apiPrefix)}/api/v1/excel/tempData/page`,
        pageSize: 20,
        sort: 'excelRowNum',
        order: 'desc',
        tabIndex:99999,// 防止菜单页tab重复
        setting: [],
        btnList: [{
          buttonName: '编辑行',
          optCode: 'edit',
          outerFlag: true
        }, {
          buttonName: '新增行',
          optCode: 'add',
          outerFlag: true
        }, {
          buttonName: '删除行',
          optCode: 'del',
          outerFlag: true
        },{
          buttonName: '校验行',
          optCode: 'check',
          outerFlag: true
        }]
      },
      tableSelected: [], // 当前选中行
      activeRow: '', // 当前编辑行的数据
      showAddDialog: false, // 是否显示新增/编辑表单
      totalNum:0,//总条数
      noPassNum:-1,//未检查通过的条数：-1未获取
      loading:'',//任务是否执行中:check 校验中 ， complete 执行导入 ， checkrow 行校验
      exportisible:false,//是否导出
      exportConfig:[{
        code: 'export_excel_task',
        name: '待处理数据导出',
        async: false, // 是否异步
        templateCode:'',// 模板code
        dataApi: `${this.taskConfig.exportTempApi}`, //  || (this.taskConfig.apiPrefix +'/api/v1/excel/tempData/export') 临时数据导出
        filtersRaw:[], // 导出符合条件的数据(当前搜索结果的数据)
        selectedRows:[],//当前所选中的数据航
        queryField:'excelRowNum'//指定行导出的字段名称
      }], // 导出配置
    }
  },

  computed: {
    nowPageShow: {
      get() {
        return this.pageShow
      },
      set(val) {
        this.$emit('update:pageShow', val)
      }
    },
    otherFilters() {
      const otherFilter= [{
        id: 'excelTaskId',
        property: 'excelTaskId',
        operator: '=',
        value: this.basicData.id
      }]
      if(this.onlyAbnormal){
        otherFilter.push({
          id: 'excelRowState',
          property: 'excelRowState',
          operator: 'in',
          value:'[0,-1]'  // 0 未检查 , 1 检查通过 ， -1 检查未通过
        })
      }
      return otherFilter
    },
    customColumnList(){
      const exclude=['id','excelTaskId','excelRowNum','excelRowState','excelRowError','createBy','createTime','lastUpdateBy','lastUpdateTime','rowNum']
      const colums=this.extColumnList.filter(v=>{
        return exclude.indexOf(v.code)===-1
      }) 
      return colums
    },
    importStateName(){
      const importState= Number(this.basicData.importState || 0)
      switch(importState){
        case 30:
          return '任务校验中'
          break;
        case 50:
          return '数据导入中'
          break;
        default:
          return ''
          break
      }
    },
  },
  watch: {
    otherFilters(val, oldVal) {
     this.$nextTick(()=>{
        this.refreshTable(true)
     })
    }
  },
  created() {
    this.taskId = this.taskBasic.id
    this.basicData = this.taskBasic
    if(this.taskConfig.exportTempApi){
      this.tableConfig.btnList.unshift({
          buttonName: '导出',
          optCode: 'export',
          outerFlag: true
        })
    }
    this.initTableHeader()
    this.refreshTaskStatus()
  },

  methods: {
    goBack() {
      this.nowPageShow = false
    },
    // 刷新任务执行状态
    refreshTaskStatus(){
      this.getErrorCount()
      this.getTaskDetail()
    },
    // 获取未校验通过的数据行总条数
    getErrorCount(){
      queryNotCheckPassNum(this.taskConfig.apiPrefix,this.taskId).then(res=>{
        this.noPassNum=res.data || 0
      })
      queryTotalNum(this.taskConfig.apiPrefix,this.taskId).then(res=>{
        this.totalNum=res.data || 0
      })
    },
    // 查询任务详情
    getTaskDetail(){
      queryTaskDetail(this.taskConfig.apiPrefix,this.taskId).then(res=>{
        if(res.data){
          const importState = Number(res.data.importState || 0) 
          const oldState = Number(this.basicData || 0)
          if(importState != oldState){
            this.$emit('change-state',importState) // 任务状态改变
          }
          this.basicData={...this.basicData,...res.data}
          if(this.loading){
            if(importState!=30 && importState!=50){
              // 执行导入后，判断任务状态若不为“写入中 50”，则置空任务执行状态
              // 执行校验后,判断任务状态若不为“校验中 30”，则置空任务执行状态
              this.loading=''
            }
          }
        }
      })
    },
    // 初始化表头数据
    async initTableHeader() {
      const params={
        apiPrefix:getApiPrefix(this.taskConfig.apiPrefix),
        templateCode:this.basicData.templateCode
      }
      await queryTableExtColumn(params).then(res => {
        const {data=[]} = res
        this.extColumnList = data.filter(v=>{
          return v.code!=='id' && v.code !='excelTaskId'
        })
      })
      const extHeader = []
      this.extColumnList.forEach(column => {
        let setting = {
          prop: column.code,
          label: column.name,
          minWidth: column.code=='excelRowNum'?'80':'150',
          type:'text',
          // formatData: (row) => {
          //   return this.getExtColumnValue(row.extAttributeColumns, column.attributeField)
          // }
        }
        if(column.code == 'excelRowNum'){
          setting.fixed='left'
        }
        if(column.code=='excelRowState'){
          setting.minWidth='100'
          setting.type='select'
          setting.propEnum={
            /* domainCode: 'marketing',
            appCode: 'price-center',
            dictTypeCode: 'EXCEL_ROW_STATE', */
            list:[
              {dictCode:'0',dictName:'未检查'},
              {dictCode:'1',dictName:'检查通过'},
              {dictCode:'-1',dictName:'检查不通过'},
            ]
          }
        }
        extHeader.push(setting)
      })
      // this.tableConfig.setting = this.tableDefaultSetting.concat(extHeader)  
      this.tableConfig.setting = extHeader
      this.isHeaderLoad = true
      this.initTableData()
    },
    /**
     * 获取动态列的值
     * @param {Array} cloumns 动态扩展数据集
     * @param {string} field 扩展字段
    */
    getExtColumnValue(cloumns, field) {
      if (!cloumns || cloumns.length === 0) return ''
      const attr = cloumns.filter(v => v.attributeField === field)
      return attr.length ? attr[0].extColumnValue : ''
    },
    /**
     * 初始化表格数据
     *
    */
    initTableData() {
      const apiUrl = `${getApiPrefix(this.taskConfig.apiPrefix)}/api/v1/excel/tempData/page`
      this.tableConfig.interfacePath = apiUrl
      this.$nextTick(() => {
        this.$refs.refTable && this.$refs.refTable.initTableData('opCondition')
      })
    },
    // 刷新表格
    refreshTable(flag) {
      this.getErrorCount()
      this.$refs.refTable && this.$refs.refTable.initTableData(flag?'opCondition':'onPage')
    },
    // 获取按钮操作
    btnOperate(code) {
      if(this.basicData.importState==60){
        this.$message.warning(`任务已完成,禁止任何操作`)
        return
      }
      if(this.basicData.importState==30 || this.basicData.importState==50){
        this.$message.warning(`${this.basicData.importState==30?'数据校验中':'数据导入中'}, 不能进行其他操作`)
        return
      }
      switch (code) {
        case 'export':
          this.handleExport()
          break
        case 'edit':
          if (this.tableSelected.length!=1) {
            this.$message.warning('请单项勾选需【编辑】的数据')
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'add':
          this.handleEdit()
          break
        case 'del':
          if (this.tableSelected.length==0) {
            this.$message.warning('请先勾选需【删除】的数据')
            return
          }
          this.handleDelete()
          break
        case 'check':
          if (this.tableSelected.length==0) {
            this.$message.warning('请先勾选待校验的数据')
            return
          }
          
          const flagArr = this.tableSelected.filter(v => v.state == 1)
          if (flagArr.length > 0) {
            this.$message.warning('只有未校验或未通过校验的数据行才能校验')
            return
          }
          const ids = this.tableSelected.map(v => {
            return v.id
          })
          this.handleCheck(ids)
          break
        default:
          break
      }
    },
    handleSelectionChange(val){
      this.tableSelected=val
    },
    // 新增/ 编辑
    handleEdit(row) {
      this.showAddDialog = true
      this.activeRow = row || ''
    },
    // 删除处理
    handleDelete() {
      const flagArr = this.tableSelected.filter(v => v.state == 1)
      if (flagArr.length > 0) {
        this.$message.warning('只有未校验或未通过校验的数据行才能删除')
        return
      }
      this.$confirm('正在操作删除当前所选的数据行，一旦删除，将无法恢复，确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.tableSelected.map(v => {
          return v.id
        })
        deleteTaskRowData(this.taskConfig.apiPrefix,this.basicData.id,ids).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '行删除成功',
              type: 'success'
            })
            this.refreshTable()
            this.refreshTaskStatus()
          }
        }).catch(() => {})
      })
    },
    // 行校验
    handleCheck(ids) {
      if(this.loading) return
      if(!ids || ids.length===0){
        this.$message.warning('请选择【校验】行')
        return 
      }
      this.loading='checkRow'
      taskRowCheck(this.taskConfig.checkRowApi,this.basicData.id,ids).then(res => {
        if (res.success === 1) {
          this.$message({
            message: res.msg || '数据行校验进行中，请刷新后查看结果',
            type: 'success'
          })
          this.refreshTaskStatus()
          this.refreshTable()
        }else{
          this.loading=''
        }
      }).catch(()=>{
        this.loading=''
      })

    },
    // 新增/编辑保存成功后的回调
    handleSubmitSuccess(data) {
      this.refreshTable(data.isNew)
      if(data.id){
        const ids=[data.id]
        this.handleCheck(ids)
      }
    },
    // 重新校验
    handleResetCheck() {
      if(this.loading) return
      this.$confirm('即将对全表数据进行全部校验，是否确认操作？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading='check'
        taskResetCheck(this.taskConfig.checkApi,this.taskId).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '已执行重新校验，请刷新后查看结果',
              type: 'success'
            })
            this.refreshTaskStatus()
            this.refreshTable()
          }else{
            this.loading=''
          }
        }).catch(()=>{
          this.loading=''
        })
      })      
    },
    // 执行导入
    handleImportTask() {
      if(this.loading) return
      this.$confirm('确定要执行【执行导入】的操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading='complete'
        taskImport(this.taskConfig.completeApi,this.taskId).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '已执行导入，请刷新后查看结果',
              type: 'success'
            })
            this.refreshTaskStatus()
            this.refreshTable()
          }else{
            this.loading=''
          }
        }).catch(()=>{
          this.loading=''
        })
      })
    },
    // 终止任务
    handleStopTask() {
      this.$confirm('确定要执行【终止任务】的操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        taskStop(this.taskConfig.apiPrefix,this.taskId).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '任务已终止',
              type: 'success'
            })
            this.goBack()
            this.$emit('change-state',70) // 任务状态改变
          }
        })
      })
    },
    // 导出临时数据表
    handleExport(){
      const configObj = this.exportConfig[0]
      configObj.selectedRows = this.tableSelected
      const defualtFilter =[{id:'excelTaskId',property:'excelTaskId',operator:'=',value:this.taskBasic.id}]
      if(this.onlyAbnormal){
        defualtFilter.push({
          id: 'excelRowState',
          property: 'excelRowState',
          operator: 'in',
          value:'[0,-1]'  // 0 未检查 , 1 检查通过 ， -1 检查未通过
        })
      }
      const filtersObj = this.$refs.refTable.getAllFilters()
      const searchBarFilter = (filtersObj.searchBarFilter || []).concat(filtersObj.combineFilter || [])
      configObj.filtersRaw = [...defualtFilter,...searchBarFilter]
      this.$set(this.exportConfig,0,configObj)
      this.exportisible=true
    }
  }
}
</script>
<style lang='scss' scoped>

</style>
